<?php

namespace App\Http\Middleware;

use App\Enum\CodeEnum;
use App\Enum\DriverEnum;
use App\Enum\TravelEnum;
use App\Lib\Jwt;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CheckUserToken
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $url = $request->path();
        if (!in_array($url, DriverEnum::ALLOW_ROUTE) && !preg_match(DriverEnum::ALLOW_ROUTE_PATTERN, $url)) {
            //1.拿到token
            $authorization = $request->header('authorization');
            if (empty($authorization)) {
                return fail(CodeEnum::SIGN_ERROR, 'token不存在2，请登录', ['url'=>$url, 'ip'=>$request->ip()]);
            }
            $token = trim(str_replace('Bearer', '', $authorization));
            try {
                //验证token
                $result = $this->_decodeJwt($token);
                $request->userId = $result['user_id'];
                Log::info('=======CheckUserToken======in=>userid='.$result['user_id']);
            } catch (Exception $e) {
                return fail(CodeEnum::SIGN_ERROR, 'token失效，请登录',$url);
            }
        }
        return $next($request);
    }

    /**
     *  解析token并验证是否过期
     *
     * @param $token
     * @return mixed
     * @throws Exception
     */
    private function _decodeJwt($token)
    {
        $result = Jwt::decodeToken($token);
        // 若过期
        if( time() - $result['iat'] > $result['exp'] ) {
            Log::notice(sprintf('token已经过期，UID=%d', $result['user_id']) );
            throw new Exception("token过期");
        }
        return $result;
    }
}

